package cn.le.config;

import cn.le.beans.vo.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Description
 * @Author le
 * @Date 2020/2/28 14:11
 * @Version 0.1
 **/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理请求对象属性不满足校验规则的异常信息
     * @param exception
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseVO exception(MethodArgumentNotValidException exception) {
        BindingResult result = exception.getBindingResult();
        final FieldError fieldError = result.getFieldError();
        exception.printStackTrace();
        return ResponseVO.failed(fieldError.getDefaultMessage());
    }

    /**
     * 其他全局异常在此捕获
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Throwable.class)
    public ResponseVO handleException(Throwable e) {
        e.printStackTrace();
        if (e instanceof IllegalArgumentException){
            return ResponseVO.failed(e.getMessage());
        }else if (e instanceof RuntimeException){
            return ResponseVO.failed(e.getMessage());
        }
        return ResponseVO.failed("操作失败");
    }
}
